//
//  CutoutCollageViewController.swift
//  SwiftPhtotEdit
//
//  Created by aw031 on 13/10/2025.
//

import UIKit
import SnapKit
import Photos


class CutoutCollageViewController: UIViewController {
    
    // MARK: - IBOutlets
    lazy var backView: UIView = {
        let view = UIView()
        view.layer.masksToBounds = true
        return view
    }()
    
    lazy var imageBGView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.cyan
        view.layer.masksToBounds = true
        return view
    }()
    
    lazy var imageView: UIImageView = {
        let imgView = UIImageView(image: KImage("123456"))
        imgView.contentMode = .scaleAspectFit
        imgView.backgroundColor = .clear
        return imgView
    }()
    
    
//    lazy var preImageView: UIImageView = {
//        let imgView = UIImageView()
//        imgView.contentMode = .scaleAspectFit
//        imgView.backgroundColor = .red
//        return imgView
//    }()
//    
    
    lazy var autoCutBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("auto", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        
        btn.setCustomImage(UIImage.init(systemName: "star"))
        btn.setCustomImage(UIImage.init(systemName: "star.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        
        btn.addTarget(self, action: #selector(autocutBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var lassoCutBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("lassoCut", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        
        btn.setCustomImage(UIImage.init(systemName: "star.hexagon"))
        btn.setCustomImage(UIImage.init(systemName: "star.hexagon.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(lassoCutBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var eraseBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("erase", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        
        btn.setCustomImage(UIImage.init(systemName: "pencil.tip.crop.circle"))
        btn.setCustomImage(UIImage.init(systemName: "pencil.tip.crop.circle.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(eraseBtnClick), for: .touchUpInside)
        return btn
    }()
    
    
    lazy var saveBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("保存", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.normalImage = UIImage.colorConversionImage(with:.lightGray)
        btn.selectImage = UIImage.colorConversionImage(with:.cyan)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
        return btn
    }()
    
    
    lazy var photoBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("photo", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.backgroundColor = .cyan
        btn.setCustomImage(UIImage.init(systemName: "photo.stack"))
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(photoClickUpInside), for: .touchUpInside)
        return btn
    }()
    
    lazy var previousStepBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("上一步", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.backgroundColor = .lightGray
        btn.setCustomImage(UIImage.init(systemName: "arrow.uturn.backward"))
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        btn.isEnabled = false
        btn.alpha = 0.5
        btn.addTarget(self, action: #selector(previousStepBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var extStepBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("下一步", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.backgroundColor = .lightGray
        btn.setCustomImage(UIImage.init(systemName: "arrow.uturn.forward"))
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        btn.isEnabled = false
        btn.alpha = 0.5
        
        btn.addTarget(self, action: #selector(nextStepBtnClick), for: .touchUpInside)
        return btn
    }()
    
    
    
    lazy var eraserIconView: UIView = {
        let view = UIImageView()
        view.backgroundColor = UIColor.red.withAlphaComponent(0.2)
        //        view.layer.cornerRadius = self.tagIconImageSize.width/2.0;
        view.layer.borderColor  = UIColor.white.cgColor
        //        view.layer.borderWidth = 2
        view.layer.masksToBounds = true
        return view
    }()
    
    
    
    // MARK: - Properties
    //擦除和刷子的path
    var erasePath: UIBezierPath?
//    //刷子
//    var restoreStack: [UIBezierPath] = []
//    //擦除
//    var brushStack: [UIBezierPath] = []
    //用于原始的图片
    var originalImage: UIImage?
    //修改的图片
    var sourceImage: UIImage?
    
    
    
//    var operationHistoryModels: [OperationHistoryModel] = []
    
//    var operationHistoryModels: [(operationType : OperationType , operationPaths : [UIBezierPath])] = []

    var operationHistoryModels: [[OperationHistoryModel]] = []
    var currentHistoryIndex: Int = -1 // 当前历史记录索引
    
    var lastTouchPoint: CGPoint = .zero
    //获取服务器抠图的图片
    var cutImage: UIImage?
    //是不是刷子的操作
    var isBrush: Bool = false
    //是否可以编辑
    var isAllowEdit: Bool = false
    
    var lastScale : CGFloat = 1
    
    lazy var pinch: UIPinchGestureRecognizer = {
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        return pinchGesture
    }()
    
    //    var taskCount: Int = 0
    //是否是放大缩小
    var isPinching: Bool = false
    //用户设置的大小默认 50
    var lineWidth : CGFloat  = 50
    //画笔的粗细
    var brushWidth : CGFloat = 50
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        // Do any additional setup after loading the view.
        
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        
        let btn = UIButton(type: .custom)
        btn.setTitle("<", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.addTarget(self, action: #selector(clickUpdataAction), for: .touchUpInside)
        self.view.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.top.equalTo(KStatusBarHeight)
            make.leading.equalTo(16)
            make.width.height.equalTo(44)
        }
        
        self.setUpDataUI()
        // 开启用户交互
        self.sourceImage = self.imageView.image
        self.originalImage = self.sourceImage
        self.imageView.isUserInteractionEnabled = true
        
        // 添加捏合手势
        pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        self.imageView.addGestureRecognizer(self.pinch)
        
        // 添加拖拽手势（仅支持双指平移）
        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        pan.minimumNumberOfTouches = 2
        pan.maximumNumberOfTouches = 2
        self.imageView.addGestureRecognizer(pan)
        
        
        self.view.layoutIfNeeded()
        self.updataLineWidth(lineWidth: self.lineWidth)
        
        // 保存初始状态到历史记录
        DispatchQueue.main.async {
            self.saveInitialState()
        }
    }
    
    
    @objc func clickUpdataAction(_ sender : UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 更好的时机
        navigationController?.navigationBar.isHidden = true
        navigationController?.setNavigationBarHidden(true, animated: false)
        
    }
    override func viewDidAppear(_ animated: Bool) {
        self.updataLineWidth(lineWidth: self.lineWidth)
    }
    
    func setUpDataUI() {
        // MARK: - IBOutlets
        view.addSubview(backView)
        backView.addSubview(imageBGView)
        imageBGView.addSubview(imageView)
        
        backView.addSubview(autoCutBtn)
        backView.addSubview(lassoCutBtn)
        backView.addSubview(eraseBtn)
        backView.addSubview(photoBtn)
        backView.addSubview(previousStepBtn)
        backView.addSubview(extStepBtn)
        backView.addSubview(saveBtn)

//        backView.addSubview(preImageView)
        
        
        let slider = SteppedSlider()
        slider.minimumValue  = 0
        slider.maximumValue = 100
        slider.changeValueBlock = { [weak self] sender in
            self?.changeLineWidthValue(sender)
        }
//        slider.addTarget(self, action: #selector(changeLineWidthValue), for: .valueChanged)
        slider.value = Float(self.lineWidth)
        
        backView.addSubview(slider)
        backView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(KStatusAndNavigationHeight)
            make.leading.bottom.trailing.equalToSuperview()
        }
        
        imageBGView.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(300)
        }
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        autoCutBtn.snp.makeConstraints { make in
            make.top.equalTo(imageBGView.snp.bottom).offset(30)
            make.leading.equalTo(16)
            make.height.equalTo(60)
        }
        
        
        
        lassoCutBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(autoCutBtn.snp.trailing).offset(16)
        }
        
        
        eraseBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(lassoCutBtn.snp.trailing).offset(16)
        }
        
        
        photoBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(eraseBtn.snp.trailing).offset(16)
        }
        
        previousStepBtn.snp.makeConstraints { make in
            make.top.equalTo(autoCutBtn.snp.bottom).offset(20)
            make.leading.equalTo(16)
            make.height.equalTo(60)
            make.width.equalTo(80)
        }
        
        extStepBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(previousStepBtn)
            make.leading.equalTo(previousStepBtn.snp.trailing).offset(16)
//            make.trailing.lessThanOrEqualTo(-16)
        }
        
        
        saveBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(previousStepBtn)
            make.leading.equalTo(extStepBtn.snp.trailing).offset(16)
            make.trailing.lessThanOrEqualTo(-16)
        }
        
        
//        preImageView.snp.makeConstraints { make in
//            make.top.equalTo(saveBtn.snp.bottom).offset(16)
//            make.leading.trailing.height.equalTo(self.imageView)
//        }
//        
        
        slider.snp.makeConstraints { make in
            make.top.equalTo(previousStepBtn.snp.bottom).offset(20)
            make.leading.equalToSuperview().offset(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(30)
        }
    }
    
    
    func setImage(_ image: UIImage) {
        self.sourceImage = image
        self.imageView.image = image
        
        self.autocutBtnClick(self.autoCutBtn)
    }
    
    @objc func changeLineWidthValue(_ sender : UISlider) {
        self.lineWidth = CGFloat(sender.value)
        
        self.updataLineWidth(lineWidth: self.lineWidth)
    }
    
    // MARK: - Button Actions
    //上一步
    @objc func previousStepBtnClick(_ sender: UIButton) {
        guard currentHistoryIndex >= 0 else { return }
        // 撤销到上一步
        loadFromHistory(index: currentHistoryIndex - 1)
        print("撤销操作，当前历史索引: \(currentHistoryIndex)")
    }
    
    //下一步
    @objc func nextStepBtnClick(_ sender: UIButton) {
        guard currentHistoryIndex < operationHistoryModels.count - 1 else { return }
        
        // 重做到下一步
        loadFromHistory(index: currentHistoryIndex + 1)
        print("重做操作，当前历史索引: \(currentHistoryIndex)")
    }
    
    @objc func autocutBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        lassoCutBtn.isSelected = false
        eraseBtn.isSelected = false
        isAllowEdit = false
        eraserIconView.isHidden = true
        
        if sender.isSelected {
            if let cutImage = self.cutImage {
                self.imageView.image = cutImage
                self.originalImage = cutImage
                
                self.resetTouchData()
                // 重置历史记录
                self.operationHistoryModels.removeAll()
                self.currentHistoryIndex = -1
                self.saveInitialState()
            } else {
                self.loadResultData(self.sourceImage)
            }
        } else {
            self.imageView.image = self.sourceImage
            self.originalImage = self.sourceImage
            
            self.resetTouchData()
            // 重置历史记录
            self.operationHistoryModels.removeAll()
            self.currentHistoryIndex = -1
            self.saveInitialState()
        }
    }
    
    //刷子
    @objc func lassoCutBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        eraseBtn.isSelected = false
        isAllowEdit = sender.isSelected

        
        if !sender.isSelected { return }
        
        self.isBrush = true
        self.originalImage = self.imageView.image
        
        //        self.eraserIconView.center = self.imageView.center
        //        self.imageView.addSubview(eraserIconView)
    }
    
    
    //擦除
    @objc func eraseBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        lassoCutBtn.isSelected = false
        isAllowEdit = sender.isSelected
        
        if !sender.isSelected { return }
        
        self.isBrush = false
        self.originalImage = self.imageView.image
        
    }
    
    @IBAction func backBtnClick(_ sender: UIButton) {
        self.backView.removeFromSuperview()
    }
    
   @objc func saveBtnClick(_ sender: UIButton) {
        // 注意：这里需要替换为实际的 PurchaseManager 和 CommonClass 实现
        /*
         if !PurchaseManager.shared.isMember && CommonClass.showCutout() {
         let vc = PremiumEditionController()
         if let currentVC = CommonClass.currentViewController() {
         currentVC.navigationController?.pushViewController(vc, animated: true)
         }
         } else {
         if self.imageView.image != nil {
         CommonClass.updateCutout(true)
         }
         
         self.saveBtnClick?(self.imageView.image)
         }
         */
        
        // 临时实现 - 直接保存，确保保存带有透明度的图片
        guard let imageToSave = self.imageView.image else {
            print("没有图片可保存")
            return
        }
               
        // 重新生成最终的图片，确保透明度正确
//       self.preImageView.image = self.imageView.image
       
       let preVC = PreViewController.init()
       preVC.preImage = self.imageView.image
       
       self.navigationController?.pushViewController(preVC, animated: true)
//       PhotoTools.saveImage(with: self.imageView.image!) { saveSuccess, error in
//           if saveSuccess {
//               print("保存成功")
//           } else {
//               print("保存失败: \(error?.localizedDescription ?? "未知错误")")
//           }
//       }

//       
//       UIImageWriteToSavedPhotosAlbum(self.imageView.image!, self, nil,nil)
    }
    
    
//    func saveTransparentImage(_ image: UIImage) {
//        // 转换为PNG数据以保持透明
//        guard let pngData = image.pngData() else { return }
//        
//        // 方法1：使用Photos Framework
//        PHPhotoLibrary.shared().performChanges({
//            let creationRequest = PHAssetCreationRequest.forAsset()
//            creationRequest.addResource(with: .photo, data: pngData, options: nil)
//        }) { success, error in
//            DispatchQueue.main.async {
//                if success {
//                    print("透明图片保存成功")
//                } else {
//                    print("保存失败: \(error?.localizedDescription ?? "未知错误")")
//                }
//            }
//        }
//        
//    }
    
//    func convertViewToImage(_ view: UIView, withCornerRadius cornerRadius: CGFloat) -> UIImage {
//        // 1. 开始图形上下文，确保指定目标大小，并使用屏幕的分辨率，支持透明度
//        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, UIScreen.main.scale)
//        defer { UIGraphicsEndImageContext() }
//        
//        // 2. 获取当前上下文
//        guard let context = UIGraphicsGetCurrentContext() else {
//            return UIImage()
//        }
//        
//        // 3. 清除背景，保持透明
//        context.clear(view.bounds)
//        
//        // 4. 缩放视图的坐标系统
//        context.scaleBy(x: view.frame.size.width / view.bounds.size.width,
//                       y: view.frame.size.height / view.bounds.size.height)
//        
//        // 5. 渲染视图到上下文
//        view.layer.render(in: context)
//        
//        // 6. 获取渲染后的图像
//        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
//            return UIImage()
//        }
//        
//        // 7. 应用圆角
//        return getCornerImageAtOriginalImageCorner(with: image,
//                                                 cornerWidth: cornerRadius,
//                                                   backgroundColor: .clear)
//    }
//    
//    func getCornerImageAtOriginalImageCorner(with image: UIImage,
//                                                 cornerWidth: CGFloat,
//                                           backgroundColor: UIColor) -> UIImage {
//        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
//        defer { UIGraphicsEndImageContext() }
//        
//        let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
//        let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
//        
//        // 只有在需要圆角时才处理，否则直接返回原图
//        if cornerWidth > 0 {
//            let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerWidth)
//            bezierPath.addClip()
//        }
//        
//        // 只有在背景色不是透明时才填充背景
//        if backgroundColor != UIColor.clear {
//            backgroundColor.set()
//            UIRectFill(bounds)
//        }
//        
//        image.draw(in: bounds)
//        
//        guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else {
//            return image
//        }
//        
//        return newImage
//    }

    
    // MARK: - Touch Handling
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isAllowEdit || isPinching { return }
        guard let touch = touches.first else { return }
        
        
        let touchInViewPoint = touch.location(in: self.imageView)
        self.eraserIconView.center = self.imageView.center
        self.imageView.addSubview(eraserIconView)
        
        eraserIconView.isHidden = false
        eraserIconView.center = touchInViewPoint
        
        if self.erasePath == nil {
            self.erasePath = UIBezierPath()
            //设置线的大小
            self.erasePath?.lineWidth = self.brushWidth
            self.erasePath?.lineCapStyle = .round
        }
        
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isAllowEdit || isPinching { return }
        
        guard let touch = touches.first else { return }
        guard let img = self.sourceImage else { return }
        
        let touchInViewPoint = touch.location(in: self.imageView)
        eraserIconView.center = touchInViewPoint
        
        guard let _ = self.originalImage else { return }
        
        
        let currentPoint = getTouchPoint(img: img, touchInViewPoint: touchInViewPoint)
        
        if self.lastTouchPoint == .zero {
            self.erasePath?.move(to: currentPoint)
        } else {
            let midPoint = CGPoint(
                x: (self.lastTouchPoint.x + currentPoint.x) / 2.0,
                y: (self.lastTouchPoint.y + currentPoint.y) / 2.0
            )
            self.erasePath?.addQuadCurve(to: midPoint, controlPoint: self.lastTouchPoint)
        }
        
        self.lastTouchPoint = currentPoint
        
        self.renderMask()
        print("touchesMoved ====  \(touchInViewPoint)")
    }
    
    // 在触摸结束时更新完整图像
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isAllowEdit || isPinching { return }
        
        if let erasePath = self.erasePath, !erasePath.isEmpty {
            let operationType: OperationType = self.isBrush ? .brush : .erase
            
            // 保存操作到历史记录
            saveToHistory(operationType: operationType,path: (erasePath.copy() as! UIBezierPath))
            // 触摸结束时更新完整图像
            updateFinalMask()
            
        }
        
        self.eraserIconView.isHidden = true
        self.erasePath = nil
        self.lastTouchPoint = .zero
        print("touchesEnded ==== ")
    }
    
    
    // MARK: - Mask Rendering (优化版)
    func renderMask() {
        guard let sourceImage = self.sourceImage else { return }
        
        UIGraphicsBeginImageContextWithOptions(sourceImage.size, false, sourceImage.scale)
        defer { UIGraphicsEndImageContext() }
        
        // 绘制上一次的完整结果作为基础
        self.originalImage?.draw(at: .zero)
        
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.saveGState()
        
        ctx.setLineCap(.round)
        ctx.setLineWidth(self.brushWidth)
        
        // 先处理当前正在进行的擦除操作
        if  let erasePath = self.erasePath  {
            
            if self.isBrush {
                ctx.saveGState()
                ctx.addPath(erasePath.cgPath)
                ctx.replacePathWithStrokedPath()
                ctx.clip()
                sourceImage.draw(at: .zero)
                ctx.restoreGState()
            }else {
                // 确保擦除操作使用透明色
                ctx.setBlendMode(.clear)
                ctx.setStrokeColor(UIColor.clear.cgColor)
                ctx.setFillColor(UIColor.clear.cgColor)
                ctx.addPath(erasePath.cgPath)
                ctx.strokePath()
                
            }

        }
        
        
        ctx.restoreGState()
        
        if let result = UIGraphicsGetImageFromCurrentImageContext() {
            self.imageView.image = result
            // 注意：这里不更新 originalImage，只在结束时更新
        }
    }
    
    
    // 更新最终掩码图像
    private func updateFinalMask() {
        guard let sourceImage = self.sourceImage else { return }
        
        UIGraphicsBeginImageContextWithOptions(sourceImage.size, false, sourceImage.scale)
        defer { UIGraphicsEndImageContext() }
        
        sourceImage.draw(at: .zero)
        
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.saveGState()
        
        ctx.setLineCap(.round)
//        ctx.setLineWidth(self.brushWidth)
        
        
        // 先处理所有擦除操作
        ctx.setBlendMode(.clear)
        ctx.setStrokeColor(UIColor.clear.cgColor)
        ctx.setFillColor(UIColor.clear.cgColor)
        
        
        
        for operationModel in self.operationHistoryModels[currentHistoryIndex] {
            
            
            ctx.setLineWidth(operationModel.path.lineWidth)
            if operationModel.operationType == .brush {
                ctx.saveGState()
                ctx.addPath(operationModel.path.cgPath)
                ctx.replacePathWithStrokedPath()
                ctx.clip()
                sourceImage.draw(at: .zero)
                ctx.restoreGState()
            }else {
                ctx.addPath(operationModel.path.cgPath)
                ctx.strokePath()
            }
        }
        
        ctx.restoreGState()
        
        if let result = UIGraphicsGetImageFromCurrentImageContext() {
            self.imageView.image = result
            self.originalImage = result
        }
    }
    
    // 获取图片中画笔的粗细比例方法：
    private func convertToImageLineWidthScale() -> CGFloat {
        guard let img = self.sourceImage else { return 1 }
        
        let imageSize = img.size
        let imageViewSize = self.imageBGView.bounds.size
        
        //        print("sourceImage 图片的大小 \(imageSize) ----- originalImage 图片的大小 \(originalImage!.size) ----imageViewSize  \(imageViewSize)")
        // 计算图像在UIImageView中的实际显示尺寸
        let imageScale = min(imageViewSize.width / imageSize.width, imageViewSize.height / imageSize.height)
        let fittedImageSize = CGSize(
            width: imageSize.width * imageScale,
            height: imageSize.height * imageScale
        )
        
        // 计算从视图坐标到图像坐标的转换比例
        let scaleToImage = imageSize.width / fittedImageSize.width
        
        return scaleToImage / (self.imageView.transform.a)
    }
    
    //获取对应手指所在位置
    func getTouchPoint(img : UIImage , touchInViewPoint : CGPoint) -> CGPoint {
        let imageSize = img.size
        let imageViewSize = self.imageView.bounds.size
        let scale = min(imageViewSize.width / imageSize.width, imageViewSize.height / imageSize.height)
        let fittedImageSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
        let x = (imageViewSize.width - fittedImageSize.width) / 2.0
        let y = (imageViewSize.height - fittedImageSize.height) / 2.0
        
        let currentPoint = CGPoint(
            x: (touchInViewPoint.x - x) * (imageSize.width / fittedImageSize.width),
            y: (touchInViewPoint.y - y) * (imageSize.height / fittedImageSize.height)
        )
        return currentPoint
    }

   
    func resetTouchData() {
        self.operationHistoryModels.removeAll()
        self.erasePath = nil
        self.lastTouchPoint = .zero
    }
    
    // MARK: - History Management
    func saveToHistory(operationType: OperationType ,path : UIBezierPath) {
        // 如果当前不在历史记录的末尾，删除后面的记录
        if currentHistoryIndex < operationHistoryModels.count - 1 {
            operationHistoryModels.removeSubrange((currentHistoryIndex + 1)...)
        }
        
        
        let model = OperationHistoryModel(path: path, operationType: operationType)
        var arr : [OperationHistoryModel] = self.operationHistoryModels.last ?? []
        arr.append(model)
        self.operationHistoryModels.append(arr)
        
        currentHistoryIndex = operationHistoryModels.count - 1
        
        // 限制历史记录数量，避免内存过大
        if operationHistoryModels.count > 20 {
            operationHistoryModels.removeFirst()
            currentHistoryIndex -= 1
        }
        
        print("当前是步下标 === \(currentHistoryIndex)")
        updateUndoRedoButtons()
    }
    
    func updateUndoRedoButtons() {
        // 更新撤销按钮状态
        previousStepBtn.isEnabled = currentHistoryIndex > 0
        previousStepBtn.alpha = previousStepBtn.isEnabled ? 1.0 : 0.5
        
        // 更新重做按钮状态
        extStepBtn.isEnabled = currentHistoryIndex < operationHistoryModels.count - 1
        extStepBtn.alpha = extStepBtn.isEnabled ? 1.0 : 0.5
    }
    // 撤销到上一步 // 重做到下一步
    func loadFromHistory(index: Int) {
        guard index >= 0 && index < operationHistoryModels.count else { return }

        // 清除当前绘制路径
        self.erasePath = nil
        self.lastTouchPoint = .zero
        
        // 更新当前历史索引
        currentHistoryIndex = index
        
        // 更新按钮状态
        updateUndoRedoButtons()
        
        // 重新渲染图像
        updateFinalMask()
    }
    
    func saveInitialState() {
        // 保存初始状态到历史记录
        let arr : [OperationHistoryModel] = []
        operationHistoryModels.append(arr)
        currentHistoryIndex = 0
        updateUndoRedoButtons()
    }
    
    // MARK: - Album
    @objc func photoClickUpInside() {
        // 需要实现权限检查和相册访问
        /*
         PermissionManager.checkPhotoLibraryPermission()
         let imagePickerController = UIImagePickerController()
         imagePickerController.delegate = self
         imagePickerController.allowsEditing = false
         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
         imagePickerController.sourceType = .photoLibrary
         self.viewController?.present(imagePickerController, animated: true)
         }
         */
        PhotoTools.shared.showPhotoAndCameraPicker(in: self, isPhoto: true, resultHandler:{ [weak self] img in
            //            self??.pushBackgroundEditVC(image: img,isPhoto: true) { image in
            //                self?.changeBackground(selectStyle: 1, colors: [], backImage: image)
            //            }
            //            if let image = info[.originalImage] as? UIImage {
            self?.sourceImage = img
            self?.imageView.image = img
            self?.autocutBtnClick(self!.autoCutBtn)
            //            }
        })
    }
    
    // MARK: - Network Requests
    func loadResultData(_ image: UIImage?) {
        guard let image = image else {
            // PSProgressHUD.showToast("The image cannot be empty", view: self)
            return
        }
        
        // PSProgressHUD.show(in: self)
        
        // 需要实现网络请求逻辑
        /*
         let request = UploadImageRequest()
         request.image = image
         
         request.startWithCompletionBlock(success: { [weak self] request in
         guard let self = self else { return }
         if let responseDict = request.responseObject as? [String: Any],
         let code = responseDict["code"] as? NSNumber, code == 0,
         let data = responseDict["data"] as? [String: Any],
         let filePath = data["filePath"] as? String {
         self.createTask(filePath)
         } else {
         // PSProgressHUD.hide(in: self)
         // PSProgressHUD.showToast("Please try again later", view: self)
         }
         }, failure: { [weak self] request, message in
         guard let self = self else { return }
         // PSProgressHUD.hide(in: self)
         // PSProgressHUD.showToast("Please try again later", view: self)
         })
         */
    }
    
    func createTask(_ filePath: String) {
        // 实现创建任务的网络请求
    }
    
    func taskStatus(_ taskId: String) {
        // 实现任务状态查询的网络请求
        
    }
    
    
    func updataLineWidth(lineWidth : CGFloat) {
        
        let scale  = convertToImageLineWidthScale()
        
        
        let iconWidth = self.lineWidth / self.imageView.transform.a
        let tempLineWidth  = self.lineWidth * scale
        
        self.eraserIconView.frame.size = CGSizeMake(iconWidth,iconWidth)
        self.eraserIconView.layer.cornerRadius = iconWidth/2.0
        self.eraserIconView.layer.borderWidth = 2 / self.imageView.transform.a
        
        self.brushWidth = tempLineWidth
        
    }
    
    @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
        guard let view = pinch.view else { return }
        
        switch pinch.state {
        case .began:
            self.isPinching = true
            self.lastScale = 1.0
            let touchInViewPoint = pinch.location(ofTouch: 0, in: self.imageView)
            eraserIconView.isHidden = true
            eraserIconView.center = touchInViewPoint
            
        case .changed:
            self.isPinching = true
            
            let currentScale = pinch.scale
            let scaleChange = currentScale / self.lastScale
            
            // 应用缩放变化
            view.transform = view.transform.scaledBy(x: scaleChange, y: scaleChange)
            self.lastScale = currentScale
            
        case .ended, .cancelled, .failed:
            self.isPinching = false
            self.lastScale = 1.0
            
            // 限制最小和最大缩放
            let minScale: CGFloat = 1
            let maxScale: CGFloat = CGFLOAT_MAX
            
            let currentScale = view.transform.a
            
            if currentScale < minScale {
                UIView.animate(withDuration: 0.2) {
                    view.transform = CGAffineTransform(scaleX: minScale, y: minScale)
                }
            } else if currentScale > maxScale {
                UIView.animate(withDuration: 0.2) {
                    view.transform = CGAffineTransform(scaleX: maxScale, y: maxScale)
                }
            }
            
            // 缩放结束后检查边界
            checkAndAdjustBounds(for: view, animated: true)
            
            updataLineWidth(lineWidth: self.lineWidth)
            print("放大缩小")
            
        default:
            break
        }
    }
    
    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
        guard let piece = pan.view, let superview = piece.superview else { return }
        let translation = pan.translation(in: superview)
        
        switch pan.state {
        case .began, .changed:
            piece.center = CGPoint(x: piece.center.x + translation.x,
                                   y: piece.center.y + translation.y)
            pan.setTranslation(.zero, in: superview)
            self.isPinching = true
            
        case .ended, .cancelled:
            self.isPinching = false
            // 平移结束后检查边界
            checkAndAdjustBounds(for: piece, animated: true)
            print("平移")
            
        default:
            break
        }
    }
    
    // 边界检查方法（只在手势结束时调用）
    private func checkAndAdjustBounds(for view: UIView, animated: Bool = false) {
        guard let superview = view.superview else { return }
        
        let transformedFrame = view.convert(view.bounds, to: superview)
        let superBounds = superview.bounds
        
        var finalFrame = transformedFrame
        var needsAdjustment = false
        
        // 检查左边界 - 如果左边界在父视图内部，就拉到左对齐
        if transformedFrame.minX > superBounds.minX {
            finalFrame.origin.x = superBounds.minX
            needsAdjustment = true
        }
        
        // 检查右边界 - 如果右边界在父视图内部，就拉到右对齐
        if transformedFrame.maxX < superBounds.maxX {
            finalFrame.origin.x = superBounds.maxX - transformedFrame.width
            needsAdjustment = true
        }
        
        // 检查上边界 - 如果上边界在父视图内部，就拉到上对齐
        if transformedFrame.minY > superBounds.minY {
            finalFrame.origin.y = superBounds.minY
            needsAdjustment = true
        }
        
        // 检查下边界 - 如果下边界在父视图内部，就拉到下对齐
        if transformedFrame.maxY < superBounds.maxY {
            finalFrame.origin.y = superBounds.maxY - transformedFrame.height
            needsAdjustment = true
        }
        
        // 如果需要调整边界
        if needsAdjustment {
            let newCenter = CGPoint(
                x: finalFrame.midX,
                y: finalFrame.midY
            )
            
            if animated {
                UIView.animate(withDuration: 0.35,
                               delay: 0,
                               usingSpringWithDamping: 0.8,
                               initialSpringVelocity: 1.0,
                               options: [.curveEaseOut]) {
                    view.center = newCenter
                }
            } else {
                view.center = newCenter
            }
        }
    }
    
    // 允许同时识别缩放和平移手势
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return (gestureRecognizer is UIPinchGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer) ||
        (gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPinchGestureRecognizer)
    }
}


